#include "thread_pool.h"
#include "virtual_file.h"
#include <openssl/sha.h>
#include <openssl/evp.h>

/* 初始化file  */
int file_init(file_t* file){
    file = (file_t*)calloc(1, sizeof(file));
    if(file == NULL){
        fprintf(stderr, "Failed to allocate memory for file_t\n");
        return -1;
    }
    memset(file, 0, sizeof(file_t));
    return 0;
}

/*生成hash值*/
int hash_sha256(char* filename, char* result){

    int fd = open(filename, O_RDONLY);
    ERROR_CHECK(fd, -1, "open");
    char buff[1000] = {0};
    int ret = 0;

    //使用EVP接口
    EVP_MD_CTX* context = EVP_MD_CTX_new();
    ERROR_CHECK(context, NULL, "EVP_MD_CTX_new");

    //初始化sha_256
    EVP_DigestInit_ex(context, EVP_sha256(), NULL);

    while(1){
        bzero(&buff, sizeof(buff));
        ret = read(fd, buff, sizeof(buff));
        if(ret == 0){
            break;
        }
        //每段内容都需要调用更新函数
        EVP_DigestUpdate(context, buff, ret);
    }

    unsigned length = 0;
    unsigned char sh[SHA256_DIGEST_LENGTH] = {0};
    EVP_DigestFinal_ex(context, sh, &length);

    for(unsigned int i = 0; i < length; i++){
        char frag[3] = {0};
        sprintf(frag, "%02x", sh[i]);
        strcat(result, frag);
    }

    printf("result:%s\n", result);
    //释放资源
    EVP_MD_CTX_free(context);

    return 0;

}

